<template>
    <div class="login-wrap">
        <div class="ms-title">{{$t('login.title')}}</div>
        <div class="ms-login">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm">
                <el-form-item prop="username">
                    <el-input v-model="ruleForm.username" :placeholder="$t('login.username')"></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input type="password" :placeholder="$t('login.password')" v-model="ruleForm.password" @keyup.enter.native="submitForm('ruleForm')"></el-input>
                </el-form-item>
                <!--<el-form-item>
                    <el-select v-model="ruleForm.userType" value="普通用户" placeholder="请选择用户类型" style="width: 100%;">
                        <el-option value="普通用户" :key="1">普通用户</el-option>
                        <el-option value="RPC用户" :key="2">RPC用户</el-option>
                        <el-option value="商户用户" :key="3">商户用户</el-option>
                    </el-select>
                </el-form-item>-->
                <el-form-item>
                    <el-select v-model="lanValue" @input="changeLan()" value="English" style="width: 100%;">
                        <el-option v-for="(val, key) in lanData" :value="key" :key="key">{{val.nativeName}}</el-option>
                    </el-select>
                </el-form-item>
                <div class="login-btn">
                    <el-button type="primary" @click="submitForm('ruleForm')">{{$t('login.loginBtn')}}</el-button>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
    import { mapGetters,mapActions,mapMutations } from 'vuex';
    import cookieFunc from '../../assets/script/cookie';
    import axios from "axios";
    import enLocale from 'element-ui/lib/locale/lang/en';
    import zhLocale from 'element-ui/lib/locale/lang/zh-CN';
    import locale from 'element-ui/lib/locale';
    import { loginURL } from "../../config/env";

    export default {
        data: function(){
            return {
                ruleForm: {
                    username: '',
                    password: '',
                    userType:1
                },
                rules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur' }
                    ]
                },
                lanValue:"中文（中国）"
            }
        },
        created() {
            let _this = this;
            _this.requestLanChoice();
            _this.getCookieChangeLan();
        },
        computed:{
            ...mapGetters([
                "lanData",
                "currentLan"
            ])
        },
        methods: {
            ...mapActions([
                'getLanChoice'
            ]),
            ...mapMutations([
                'setCurrentLan',
                'saveValidatePassword'
            ]),
            elementLocales(elLocale) {
                if(elLocale === 'en-US'){
                    locale.use(enLocale);
                }else if(elLocale === 'zh-CN'){
                    locale.use(zhLocale);
                }
            },
            // 请求语言选项文件
            requestLanChoice() {
                this.getLanChoice(this.$i18n.messages["allLan"]);
                sessionStorage.setItem('lanChoice', JSON.stringify(this.$i18n.messages["allLan"]));
            },
            changeLan() {
                console.log(this.lanData[this.lanValue]);
                cookieFunc.setCookie("lanName",this.lanValue,"h1");
                this.setCurrentLan(this.lanValue);
                this.$i18n.locale = this.lanValue;
                this.elementLocales(this.lanValue);
                this.lanValue = this.lanData[this.lanValue].nativeName;
            },
            getCookieChangeLan() {
                if (cookieFunc.getCookie("lanName") !== null) {
                    let cookieLanName = cookieFunc.getCookie("lanName");
                    console.log(cookieLanName);
                    console.log(this.lanData[cookieLanName]);
                    this.setCurrentLan(cookieLanName);
                    this.$i18n.locale = cookieLanName;
                    this.elementLocales(cookieLanName);
                    this.lanValue = this.lanData[cookieLanName].nativeName;
                }else{
                    if(this.currentLan !== ''){
                        this.$i18n.locale = this.currentLan;
                        this.elementLocales(this.currentLan);
                        this.lanValue = this.lanData[this.currentLan].nativeName;
                    }else{
                        //检测浏览器语言
                        let currentLang = navigator.language;   //判断除IE外其他浏览器使用语言
                        if(!currentLang){//判断IE浏览器使用语言
                            currentLang = navigator.browserLanguage;
                        }
                        this.$i18n.locale = currentLang;
                        this.elementLocales(currentLang);
                        this.lanValue = this.lanData[currentLang].nativeName;
                    }
                }
            },
            submitForm(formName) {
                const self = this;
//                self.$router.push('/taskCronerAlertConfig');
                self.$refs[formName].validate((valid) => {
                    if (valid) {
                        /*if(self.ruleForm.userType === '普通用户') {
                            self.ruleForm.userType = 1;
                        }else if(self.ruleForm.userType === 'RPC用户'){
                            self.ruleForm.userType = 2;
                        }else if(self.ruleForm.userType === '商户用户'){
                            self.ruleForm.userType = 3;
                        }*/
                        axios.post(loginURL + '/api/auth/login',this.ruleForm,{
                            headers: {'X-Requested-With':'XMLHttpRequest'}
                        }).then((res) => {
                            sessionStorage.setItem("token",res.data.token);
                            sessionStorage.setItem("refreshToken",res.data.refreshToken);
                            sessionStorage.setItem("username",self.ruleForm.username);
                            self.saveValidatePassword(self.ruleForm.password);
                            self.$router.push({ path: '/dashboard/dashboard' });
                        }).catch((error) => {
                            if (error.message.indexOf('Network Error') !== -1) {
                                self.$message.error('登录超时！！');
                            }else if(error.message.indexOf('Request failed with status code 401') !== -1) {
                                self.$message.error('账号或密码错误！！');
                            }

                        });
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        }
    }
</script>

<style lang="stylus">
    .login-wrap
        position:relative
        width:100%
        height:100%
        .ms-title
            position: absolute
            top:50%
            width:100%
            margin-top: -230px
            text-align: center
            font-size:30px
            color: #fff
        .ms-login
            position: absolute
            left:50%
            top:50%
            width:300px
            height:212px
            margin:-150px 0 0 -190px
            padding:40px
            border-radius: 5px
            background: #fff
            .login-btn
                text-align: center
                button
                    width:100%
                    height:36px
</style>
